﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceConsumer;
using System.Data;
using System.Data.Linq;

public partial class Checkout : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {        
        if (Session["Cart"] == null)
        {
            Response.Redirect("~/Cart.aspx");
        }

        List<TaiLieu> lst = (List<TaiLieu>)Session["Cart"];
        if (lst.Count == 0)
        {
            Response.Redirect("~/Cart.aspx");
        }

        if (Session["TaiKhoan"] == null)
        {
            Session["Redirect"] = "~/Checkout.aspx";
            Response.Redirect("~/Login.aspx");
        }

        if (Session["CitiesList"] == null)
        {
            //string strUrlWS = "http://aspspider.info/m15tmdt/WebService.asmx";
            //string strUrlWS = "http://moving10ws.somee.com/service.asmx";
            //string sFromCity = "46";
            //object[] para = null;

            //object lstCity = WSProxy.CallWebService(strUrlWS, "CitiesList", null);
            //DataTable dtCities = WSProxy.ConvertType<DataTable>(lstCity);

            CarrierServices carrier = new CarrierServices();
            DataTable dtCities = carrier.CitiesList();

            Session["CitiesList"] = dtCities;
        }

        if (Request.Form["checkOut"] != null)
        {
            try
            {
                //Response.Write("abc def");
                string strHoTen = Request.Form["txtLastName"];
                string strTinhThanh = Request.Form["dbcboCountries"];
                string strDiaChi = Request.Form["txtAddress"];
                string strDiaChiThuHai = Request.Form["txtAddress2"];
                string strCMND = Request.Form["txtPostCode"];
                string strDienThoaiDD = Request.Form["txtCity"];
                string strDienThoaiBan = Request.Form["txtPhone"];

                int iRememberCard = 0;
                if (Request.Form["txtRemembercard"].ToString().Equals("true"))
                {
                    iRememberCard = 1;
                }

                string strMaThe = Request.Form["txtCardNumber"];
                string strMaBaoMat = Request.Form["txtSecurityNumber"];

                string strThang = Request.Form["cboMonth"];
                string strNam = Request.Form["cboYear"];
                string strNgayHetHan = strNam + "-" + strThang + "-01";

                string strTenChuThe = Request.Form["txtFirstName"];

                //string strMoiGioi = Request.Form["dbcboBanks"];
                //DateTime dtNgayHetHan = new DateTime();

                string strTongTien = Request.Form["totalPrice"];

                List<TaiLieu> lstTL = (List<TaiLieu>)Session["Cart"];

                NhaKinhDoanhDataContext db = new NhaKinhDoanhDataContext();
                TaiKhoan tk = (TaiKhoan)Session["TaiKhoan"];

                PhieuDatHang pdh = new PhieuDatHang();
                pdh.MaKhachHang = tk.MaKhachHang;
                pdh.MaThanhPhoDen = strTinhThanh;
                pdh.NgayDatHang = DateTime.Now;
                pdh.ThanhTien = float.Parse(strTongTien);
                pdh.MaTinhTrang = 0;

                Application.Lock();

                List<string> lstDemension = new List<string>();

                EntitySet<CTPhieuDatHang> esCTPDH = new EntitySet<CTPhieuDatHang>();

                float fTongTien = 0;

                for (int i = 0; i < lstTL.Count; i++)
                {
                    CTPhieuDatHang ct = new CTPhieuDatHang();
                    ct.MaTaiLieu = lstTL[i].ProductID;
                    ct.GiaBan = lstTL[i].ProductPrice;
                    ct.SoLuong = lstTL[i].ProductQuantity;
                    ct.MaCTPDH = i + 1;
                    ct.LoaiSanPham = int.Parse(lstTL[i].DanhMuc.DanhMucCha.ParentCatID);
                    
                    if (ct.LoaiSanPham == 2)
                    {
                        lstDemension.Add(lstTL[i].Dimension);
                    }

                    esCTPDH.Add(ct);                   
                    
                    //Cập nhật lại số lượng và lượng mua của tài liệu
                    var queryUpdateView = (from obj in db.TaiLieus
                                           where obj.ProductID.Equals(ct.MaTaiLieu)
                                           select obj).Single();

                    if (ct.SoLuong > queryUpdateView.ProductQuantity)
                    {
                        ct.SoLuong = queryUpdateView.ProductQuantity;
                    }

                    fTongTien = (float)ct.SoLuong * (float)ct.GiaBan;

                    queryUpdateView.ProductQuantity-=ct.SoLuong;
                    queryUpdateView.NumsBuy+=ct.SoLuong;
                    db.SubmitChanges();
                }
              
                //string strUrlWS = "http://aspspider.info/m15tmdt/WebService.asmx";
                //string strUrlWS = "http://moving10ws.somee.com/service.asmx";
                //string sFromCity = "46";
                //List<object> paras = new List<object>();
                //string fromCity = "1";
                //string toCity = "15";

                string sDimension = DimensionCalculation.Calc(lstDemension.ToArray());

                //string sTranportType = "0";
                //paras.Add(fromCity);
                //paras.Add(toCity);
                //paras.Add(sDimension);
                //paras.Add(sTranportType);

                //object oTranportPrice = WSProxy.CallWebService(strUrlWS, "RoutePrice", paras.ToArray());

                int iTransportType = int.Parse(Request.Form["dbcboTranportTypes"]);

                if (lstDemension.Count > 0)
                {
                    CarrierServices carrier = new CarrierServices();

                    pdh.PhiVanChuyen = carrier.RoutePrice(strTinhThanh, sDimension, iTransportType);

                    pdh.ThongTinVanChuyen = iTransportType + "_" + sDimension;
                    pdh.MaNhaVanChuyen = carrier.GetCarrierID();
                }
                else
                {
                    pdh.ThongTinVanChuyen = "-";
                }

                pdh.DiaChiGiaoHang = strDiaChi;
                pdh.DiaChiThuHai = strDiaChiThuHai;
                pdh.DienThoaiLienHe = strDienThoaiDD;
                pdh.DienThoaiBan = strDiaChiThuHai;
                //pdh.MaBaoMatThe = "*************" + strMaThe.Substring(13, strMaThe.Length - 13);
                pdh.MaBaoMatThe = strMaThe.Substring(13, strMaThe.Length - 13);
                
                pdh.CTPhieuDatHangs = esCTPDH;

                db.PhieuDatHangs.InsertOnSubmit(pdh);

                var query = (from kh in db.KhachHangs
                             where kh.MaKhachHang == tk.MaKhachHang
                             select kh).Single();
                query.TenKhachHang = strHoTen;
                query.DiaChi = strDiaChi;
                query.DiaChiThuHai = strDiaChiThuHai;
                query.CMND = strCMND;
                query.DienThoaiCoDinh = strDienThoaiBan;
                query.SoDienThoai = strDienThoaiDD;
                if (query.TheThanhToan == null)
                {
                    query.TheThanhToan = new TheThanhToan();
                }
                query.TheThanhToan.MaKhachHang = query.MaKhachHang;
                query.TheThanhToan.MaTheThanhToan = strMaThe;

                try
                {
                    query.TheThanhToan.NgayHetHan = Convert.ToDateTime(strNgayHetHan);
                }
                catch
                {
                    query.TheThanhToan.NgayHetHan = null;
                }

                query.TheThanhToan.MaBaoMatThe = strMaBaoMat;
                query.TheThanhToan.TenChuThe = strTenChuThe;
                query.GhiNhoThe = iRememberCard;

                query.TinhThanh = strTinhThanh;

                db.SubmitChanges();               
                
                Session["Cart"] = null;

                Session["TaiKhoan"] = query.TaiKhoan;

                Application.UnLock();

                Response.Redirect("~/MyAccount.aspx");
            }
            catch (Exception ex)
            {
                Label1.Text = "<center><h2 style='color:red;'>" + ex.Message + "</h2></center>";
                Label1.Visible = true;
            }
        }
    }
}